import React from 'react';
import { Form, Input, Button, Card, message } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { login } from '../../services/api';
import { useNavigate } from 'react-router-dom';

const Login = () => {
  const navigate = useNavigate();

  const onFinish = async (values) => {
    try {
      const response = await login(values); // 调用api.js中的login方法发起请求，返回的response是服务器返回的json格式数据
      if (response.code === 200) {
        sessionStorage.setItem('user', JSON.stringify(response.data)); // 将用户信息存储到sessionStorage中  
        message.success('登录成功');
        navigate('/assets');
      } else {
        message.error(response.message || 'react用户身份验证失败'); // 打印服务器返回的错误message
      }
    } catch (error) {
      message.error('react请求登录失败');
    }
  };

  // 主表单绑定onFinish函数，From.Item绑定name属性。数据以 name为键名存储，自动包装为json格式的values对象.
  return (
    <div style={{ height: '100vh', display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
      <Card title="资产管理系统" style={{ width: 400 }}>
        <Form name="login" onFinish={onFinish}>
          <Form.Item name="username" rules={[{ required: true, message: '请输入用户名' }]}>
            <Input prefix={<UserOutlined />} placeholder="用户名" />
          </Form.Item>

          <Form.Item name="password" rules={[{ required: true, message: '请输入密码' }]}>
            <Input.Password prefix={<LockOutlined />} placeholder="密码" />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" block>登录</Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default Login; 